package com.david.tvhelperapp

import com.david.tvhelperapp.msgdealers.AMsgDealer
import org.json.JSONObject
import java.net.DatagramPacket
import java.net.DatagramSocket


/**
 *
 * 发送示例：
 * public static void sendUdpData(String msg) throws IOException {
 * DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
 * //确定好数据后，并把数据封装成数据包
 * byte[] buf = msg.getBytes();
 * DatagramPacket dp =
 * new DatagramPacket(buf,buf.length, InetAddress.getByName("30.11.173.6"),30000);//发送至指定IP，指定端口
 * ds.send(dp);//通过send方法将数据包发送出去
 * ds.close();//关闭资源
 * }
 *
 *
 *
 *
 * 接收示例：
 * @SuppressWarnings("resource")
 * DatagramSocket ds = new DatagramSocket(30000);//接收端监听指定端口
 * //定义数据包,用于存储数据
 * byte[] buf = new byte[10240];
 * DatagramPacket dp = new DatagramPacket(buf,buf.length);
 * while(true)
 * {
 * ds.receive(dp);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
 * //通过数据包的方法获取其中的数据
 * String ip = dp.getAddress().getHostAddress();
 * String data = new String(dp.getData(),0,dp.getLength());
 * Log.e("udp", "udp data is " + data + ";ip is " + ip);
 * }
 * */
class TvMsgReceiver {
    companion object{
        private var instance: TvMsgReceiver = TvMsgReceiver()
        fun getTvInstance(): TvMsgReceiver {
//            if (instance == null) {
//                synchronized(TvMsgReceiver::class.java) {
//                    if (instance == null) {
//                        instance = TvMsgReceiver()
//                    }
//                }
//            }
            return instance
        }
    }
    private fun TvMsgReciver() {

    }

    lateinit var channelMsgDealer:AMsgDealer


    @Volatile var msgListeners:ArrayList<IMsgListener>  = ArrayList()//使用观察者集合或者责任链模式处理数据

    @Volatile var isRunning = false;


    fun addMsgListener(msgListener:IMsgListener){
        msgListeners.add(msgListener)
    }

    fun removeMsgListener(msgListener:IMsgListener){
        msgListeners.remove(msgListener)
    }

    fun startReceive() {
        if (!isRunning) {
            Thread() {
                kotlin.run {
                    val ds = DatagramSocket(30000)//接收端监听指定端口
                    //定义数据包,用于存储数据
                    val buf = ByteArray(10240)
                    val dp = DatagramPacket(buf, buf.size)
                    isRunning = true
                    try {
                        while (true) {
                            ds.receive(dp)//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
                            //通过数据包的方法获取其中的数据
                            val ip = dp.address.hostAddress
                            val data = String(dp.data, 0, dp.length)

                            inner@ for (item in msgListeners) {
                                if (item.onMsgArrived(ip, data)) {
                                    break@inner
                                }
                            }

                            /**传过来格式化数据*/
                            if (data.startsWith("{")) {
                                val jsonObject = JSONObject(data)
                                val msgBean = MsgBean()
                                msgBean.action = jsonObject.getString("action")
                                msgBean.actionType = jsonObject.getString("actionType")
                                var tempMsgDealer:AMsgDealer? = channelMsgDealer
                                inner@while (tempMsgDealer != null) {
                                    if (tempMsgDealer.dealMsg(ip, msgBean)) {
                                        break@inner
                                    }
                                    tempMsgDealer = tempMsgDealer.nextDealer
                                }

                            } else {
                                /**传过来文本数据*/
                                var tempMsgDealer:AMsgDealer? = channelMsgDealer
                                inner@while (tempMsgDealer != null) {
                                    if (tempMsgDealer.dealMsg(ip, data)) {
                                        break@inner
                                    }
                                    tempMsgDealer = tempMsgDealer.nextDealer
                                }
                            }

                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    isRunning = false
                }
            }.start()
        }
    }


}